//
//  BKFeaturedViewController.m
//  bestkeep
//
//  Created by yons on 16/11/29.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKFeaturedViewController.h"
#import "BKFeaturedTableViewCell.h"
#import "BKMainCommon.h"

@interface BKFeaturedViewController ()<UITableViewDelegate,UITableViewDataSource, UIGestureRecognizerDelegate>

@property(nonatomic,strong)UITableView *myTableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSString *size;
@property(nonatomic,strong)UIButton *backButton;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)NSString *numberOfPage;

@end

@implementation BKFeaturedViewController


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = @"精选商品";
    if (self.isfirst == NO) {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
   }
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:animated];
    if(_myTableView != nil){
        [self scrollViewDidScroll:_myTableView];
    }
    self.isfirst = NO;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.title = @"";
    self.navigationController.navigationBarHidden = NO;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = YES;
    self.page = 1;
    [self requestDataWithPage:self.page size:10];
    [self greatView];
    [self setBackBtn];
    [self setRefresh];
    
}

#pragma mark --------------设置刷新-----------------

-(void)setRefresh{
    MJRefreshGifHeader *headerRefresh = [BKRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    _myTableView.mj_header = headerRefresh;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
    footer.stateLabel.textColor = LoadMoreDataTitleColor;
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color=IndictorViewColor;
    [footer addSubview:loadingView];
    _myTableView.mj_footer = footer;
    _myTableView.mj_footer.automaticallyHidden = YES;
}
-(void)refreshData{
    self.page = 1;
    [self.dataArray removeAllObjects];
    _myTableView.tableFooterView = nil;
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(updateMore)];
    footer.stateLabel.textColor = LoadMoreDataTitleColor;
    footer.stateLabel.font = [UIFont systemFontOfSize:14];
    footer.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    UIActivityIndicatorView *loadingView = [footer valueForKeyPath:@"loadingView"];
    loadingView.hidesWhenStopped = YES;
    loadingView.color=IndictorViewColor;
    [footer addSubview:loadingView];
    _myTableView.mj_footer = footer;
    _myTableView.mj_footer.automaticallyHidden = YES;

    [self requestDataWithPage:1 size:10];
}
-(void)updateMore{
    
    if ([self.numberOfPage integerValue] > 0) {
        if (self.page < [self.numberOfPage integerValue]) {
            self.page +=1;
            [self requestDataWithPage:self.page size:10];
            
            
        }else{
            [_myTableView.mj_footer endRefreshing];
            _myTableView.mj_footer = nil;
            _myTableView.tableFooterView = [PromptTools getViewWhenDataEndLoading];
        }
        
        
    }else{
        
        [_myTableView.mj_footer endRefreshing];
        _myTableView.mj_footer = nil;
    }
}
#pragma mark  -------------scrollViewDelegate---------------
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y < 0) {
        [self setStatusBarStyle:UIStatusBarStyleDefault];
        _backButton.hidden = YES;
    }else if(scrollView.contentOffset.y < 50) {
        self.navigationController.navigationBarHidden = YES;
//        [self.navigationController setNavigationBarHidden:YES animated:NO];
        [self setStatusBarStyle:UIStatusBarStyleLightContent];
        _backButton.hidden = NO;
        
    }else{
        self.navigationController.navigationBarHidden = NO;
//        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [self setStatusBarStyle:UIStatusBarStyleDefault];
        _backButton.hidden = YES;
        
    }
    
    
}
-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setBackBtn{
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _backButton.frame = CGRectMake(0, 30, 32, 18);
    [_backButton setImage:[UIImage imageNamed:@"BKFeatured_baijiantou"] forState:UIControlStateNormal];
    [_backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview: _backButton];
}

-(void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle{
    if (IOS_VERSION>=7.0){
        if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
//            [self setEdgesForExtendedLayout:UIRectEdgeNone];
        }
        [[UIApplication sharedApplication] setStatusBarStyle:statusBarStyle animated:NO];
    }
}

-(void)greatView{
    
    _myTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _myTableView.backgroundColor = RGBACOLOR(136, 136, 136, 0.1);
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.showsHorizontalScrollIndicator = NO;
    _myTableView.delegate = self;
    _myTableView.dataSource = self;
    [_myTableView registerClass:[BKFeaturedTableViewCell class] forCellReuseIdentifier:@"cell"];
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_myTableView];
    [_myTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsZero);
    }];
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    UIImage *image = [UIImage imageNamed:@"BKMain_jingxuan"];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 150 * ScreenWidth / 375)];
    imageView.image = image;
    [headerView addSubview:imageView];
    
    UILabel *wellLabel = [[UILabel alloc] init];
    wellLabel.numberOfLines = 0;
    wellLabel.font = [UIFont systemFontOfSize:12];
    wellLabel.textColor = RGBACOLOR(136, 136, 136, 1);

    NSString *str1 = @"       我们以去除商品中间化、回归商品本来价值为目的。与多家优秀品牌制造商合作，并严格把控商品生产环节。通过直连消费者和厂家，去除中间成本。秉承用户为先理念，以更低的成本享受更舒适、精致的生活，让美好生活并不昂贵。";
    
    
    NSMutableAttributedString *attributeStr1 = [[NSMutableAttributedString alloc]initWithString:str1];
    
    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc]init];
    //设置行间距
    [paragraphStyle1 setLineSpacing:5];
    //NSParagraphStyleAttributeName;(段落)
    [attributeStr1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attributeStr1 length])];
    //设置字体大小
    [attributeStr1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12]range:NSMakeRange(0, [attributeStr1 length])];
    CGSize labelSize = [attributeStr1 boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 20,MAXFLOAT)options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading context:nil].size;
    wellLabel.attributedText = attributeStr1;
    if (iPhone5 || iPhone4s) {
        wellLabel.frame = CGRectMake(20, 163 * ScreenWidth / 375, ScreenWidth - 38, labelSize.height);
    }else{
        wellLabel.frame = CGRectMake(23, 163 * ScreenWidth / 375, ScreenWidth - 40, labelSize.height);
    }
    
    wellLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [headerView addSubview:wellLabel];
    if (iPhone5 || iPhone4s) {
        headerView.frame = CGRectMake(0, 0, ScreenWidth, imageView.frame.size.height + labelSize.height + 22);
    }else{
        headerView.frame = CGRectMake(0, 0, ScreenWidth, imageView.frame.size.height + labelSize.height + 25);
    }
    
    _myTableView.tableHeaderView = headerView;
    
}

#pragma mark -- 数据请求

-(void)requestDataWithPage:(NSInteger )page size:(NSInteger)size{
    if ([BKMainCommon checkNetWork] == NO) {
        [HUD showMessage:@"请检查您的网络"];
        [self.myTableView.mj_header endRefreshing];
        [self.myTableView.mj_footer endRefreshing];
    }else{
        NSString *pageStr = [NSString stringWithFormat:@"%ld",(long)page];
        NSString *sizeStr = [NSString stringWithFormat:@"%ld",(long)size];
        [BKMainCommon getFeaturedData:pageStr size:sizeStr callback:^(id obj, NSError *error) {
            
            if (obj) {
                if (self.page == 1) {
                    NSMutableArray *itemArr = [obj objectForKey:@"list"];
                    self.dataArray = [NSMutableArray arrayWithArray:itemArr];
                }else{
                    
                    NSArray *itemArray = [obj objectForKey:@"list"];
                    for (NSDictionary *dic in itemArray) {
                        [self.dataArray addObject:dic];
                    }
                    
                    
                    
                }
                
                self.numberOfPage = [obj objectForKey:@"totalPage"];
                [self.myTableView reloadData];
                [self.myTableView.mj_header endRefreshing];
                [self.myTableView.mj_footer endRefreshing];
            }
            
            NSLog(@"%@",error);
        }];

    }
    
}

#pragma mark -----------------tableViewdelegate------------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.dataArray.count != 0) {
        return self.dataArray.count;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    BKFeaturedTableViewCell *cell = [_myTableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    if (self.dataArray.count != 0) {
        NSDictionary *itemDic = [self.dataArray objectAtIndex:indexPath.section];
        bkjxModel *model = [[bkjxModel alloc]init];
        [model setValuesForKeysWithDictionary:itemDic];
        [cell.goodsImageView load:model.goodsCoverImg placeholderImage:[UIImage imageNamed:@"BKFeatured_newGoods"]];
        cell.titleLabel.text = model.goodsSpecialDescribe;
//        cell.titleLabel.text = @"电视剧和鞭策居委会不出去备查簿惹了我会受到残酷的保护层路桥网";
        cell.desLabel.text = model.goodsName;
//        cell.desLabel.text = @"电视剧和鞭策居委会不出去备查簿惹了我会受到残酷的保护层路桥网";;
        cell.goodsPriceLabel.text = [NSString stringWithFormat:@"电动车昆明大场面%@",model.goodsPrice];
        cell.marketPriceLabel.text = model.goodsMarketPrice;
        if (model.upText == nil) {
            model.upText = @"";
        }
        
        cell.goodsPriceLabel.attributedText = [BKMainCommon specialStringStyle:[NSString stringWithFormat:@" ¥ %@%@", model.goodsPrice, model.upText] fontOfSize:12];
        [cell.lookButton addTarget:self action:@selector(lookNow:) forControlEvents:UIControlEventTouchUpInside];
        cell.lookButton.tag = indexPath.section;
    }
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 140;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 5;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.myTableView.mj_header endRefreshing];
    
    if (self.myTableView.mj_header.state == MJRefreshStateIdle) {
        [self pusthToDetail:indexPath.section];
    }
    
}

-(void)lookNow:(UIButton*)sender{
    [self pusthToDetail:sender.tag];
}

-(void)pusthToDetail:(NSInteger)index{
    if (self.dataArray.count != 0 ) {
        self.navigationController.navigationBarHidden = NO;
        NSDictionary *dic = [self.dataArray objectAtIndex:index];
        bkjxModel *model = [[bkjxModel alloc]init];
        [model setValuesForKeysWithDictionary:dic];
        Mediator *mediator = [Mediator sharedInstance];
        UIViewController *detailVC = [mediator BKGD_goodsDetailViewController:model.goodsId saleTypes:model.saleTypes];
        detailVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
